package cn.liwq.demo.java.raw.ver8.lambda;

import cn.liwq.demo.java.raw.ver8.lambda.entry.Album;
import cn.liwq.demo.java.raw.ver8.lambda.entry.Artist;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static java.util.stream.Collectors.toList;

public class LambdaTest {
    public static void main(String[] args) {

        System.out.println(addUp(Stream.of(1, 2, 3, 4, 5)));

        List<Artist> artists = Arrays.asList(new Artist("liwq", "china"), new Artist("Jack", "America"),
                new Artist("SuperStarClub", "U.K."));
        System.out.println(artistInfo(artists));

        List<Album> albums = Arrays.asList(new Album(Arrays.asList("s1", "s2", "s3", "s4")),
                new Album(Arrays.asList("a1", "a2", "a3", "a4")), new Album(Arrays.asList("v1", "v2")));
        albumsSongNumGt3(albums).forEach(album -> System.out.println(album.getTrackList()));

        artists.get(2).addMembers(new Artist("a", "U.K."));
        artists.get(2).addMembers(new Artist("b", "U.K."));
        artists.get(2).addMembers(new Artist("c", "U.K."));
        artists.get(2).addMembers(new Artist("d", "U.K."));
        System.out.println(artists.stream().map(artist -> (int) artist.getMembers().count()).reduce(0, Integer::sum));
        System.out.println(artists.stream().mapToInt(artist -> (int) artist.getMembers().count()).sum());

        String str = "abcdABCD";
        System.out.println(countLowerCaseNums(str));

        List<String> strList = Arrays.asList("aABCD", "abABCD", "abcABCD", "abcdABCD");
        System.out.println(strList.stream().max(Comparator.comparing(LambdaTest::countLowerCaseNums)).get());
        System.out.println(strList.stream().mapToLong(LambdaTest::countLowerCaseNums).max());

        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
        // 获取空字符串的数量
        System.out.println(strings.parallelStream().filter(string -> string.isEmpty()).count());
        System.out.println(strings.stream().filter(string -> string.isEmpty()).count());
    }

    public static long countLowerCaseNums(String str) {
        return str.chars().filter(Character::isLowerCase).count();
    }

    private static int addUp(Stream<Integer> numbers) {
        return numbers.reduce(0, (acc, element) -> acc + element);
    }

    private static List<String> artistInfo(List<Artist> artists) {
        return artists.stream().flatMap(artist -> Stream.of(artist.getName(), artist.getNationality()))
                .collect(toList());
    }

    private static List<Album> albumsSongNumGt3(List<Album> albums) {
        return albums.stream().filter(album -> album.getTrackList().size() > 3).collect(toList());
    }

}
